package it.laitspa.farmaceutica.online.breadcrumb;


import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;

/**
 * Breadcrumb
 * @author mtraversari
 */
public class Breadcrumb {
	
	private TrailHandler trailHandler = null;
	
	private LinkedList<Trail> trails = null;
	
	public Breadcrumb() {
		trails = new LinkedList<Trail>();
		trailHandler = new TrailHandler();
	}
	
	
	public void addTrail(String label, 
			String contextPath, 
			String path,
			String method,
			HashMap<String, String> params) {
		StringBuilder b = new StringBuilder();
		b.append(normalizeSlash(contextPath, false));
		b.append(path).append(".do?method=").append(method);
		if (params != null) {
			Iterator<String> iterator = params.keySet().iterator();
			while (iterator.hasNext()) {
				String paramName = iterator.next();
				String paramValue = params.get(paramName);
				b.append("&").append(paramName).append("=").append(paramValue);
			}
		}		
		addTrail(new Trail(label, b.toString()));
	}	
	
	private void addTrail(Trail trail) {
		Trail t = checkTrails(trail);
		if (t == null) {
			trails.add(trail);
		} else {
			trailHandler.removeItems(trails);
		}
	}
	
	public String render() {
		StringBuilder b = new StringBuilder();
		Iterator<Trail> iterator = trails.iterator();
		while (iterator.hasNext()) {
			Trail trail = iterator.next();
			b.append("<a href=\"").append(trail.getLink()).append("\">");
			b.append(trail.getLabel());
			b.append("</a>");
			b.append(" &gt; "); 			
		}
		String strip = b.toString();
		strip = strip.substring(0, strip.length() - 6);
		return strip;
	}
	
	private Trail checkTrails(Trail trail) {
		Trail tf = null;
		Iterator<Trail> iterator = trails.iterator();
		int i = 0;
		int index = 0;
		while (iterator.hasNext() && tf == null) {
			Trail t = iterator.next();
			if (t.getLabel().equals(trail.getLabel())) {
				tf = t;
				index = i;
			} 
			i++;
		}
		if (tf != null) {
			int size = trails.size();
			for (int j = 0; j < size; j++) {
				Trail tr = trails.get(j);
				if (j > index) {
					tr.setGood(false);
				} else {
					tr.setGood(true);
				}
			}
		}
		return tf;
	}
	
	private String normalizeSlash(String str, boolean isAdd) {
		String fileSeparator = "/";
		int len = str.length();
		boolean isLastSlash = str.substring(len - 1).equals(fileSeparator);		
		if (isLastSlash && !isAdd) {
			str = str.substring(0, len - 1);
		} else if (!isLastSlash && isAdd) {
			str = str + fileSeparator;
		}
		return str;
	}
}
 